<?php

namespace dexcedu;

require __DIR__ . '/../vendor/autoload.php';

// 命名空间声明要放在其他代码之前


use Workerman\Worker;

if (strtolower($_SERVER['REQUEST_METHOD']) == 'options') {
    exit;
}
extract(DBFIG);
$tpl = '%s:host=%s;dbname=%s;port=%s;charset=%s';
$args = [$type, $host, $dbname, $port, $charset];
$dsn = sprintf($tpl, ...$args);
$model = new Model($dsn, $username, $password);
//秘钥 用作登录修改的
$secretKey = '93a1c3a4b6e9f0d1e4b0f78a9cd7b0d1a78d9b0e4b0e';
$Websocket =   new Websocket($model, $secretKey);

$ws_worker = new Worker("websocket://0.0.0.0:14631");
$ws_worker->count = 1;

// 保存连接的数组，用来存储客户端连接
// 这玩意没法用
$connections = [];
$user = [];

$ws_worker->onConnect = function ($connection) use ($Websocket, &$connections, &$user) {
    // 将新连接加入连接数组

    $connection->onWebSocketConnect = function ($connection, $http_header) use ($Websocket,  &$connections, &$user) {

        $userId = $_GET['jwt'];

        if (isset($userId)) {
            // 获取用户 ID，并将其与连接关联起来
            $data = $Websocket->validateJWT($userId);
            //
            $user[$data['id']] = $data;
            $connections[$data['id']] = $connection;
            // $array['1'] = $connection;
            $connection->send(json_encode('nihao'));
        }
    };
};

$ws_worker->onMessage = function ($connection, $data) use ($Websocket, &$connections) {


    // 准确的会有是谁  发给谁  什么消息
    $message = json_decode($data, true);
    $data = $Websocket->validateJWT($message['JWT']);
    $msg = ['from' => $data, 'to' => $message['to'], 'msg' => $message['msg']];
    if ($connections[$message['to']]) {
        $connections[$message['to']]->send(json_encode($msg));
    } else {
        $connection->send(json_encode(['没在线']));
    }
};
// [1,mesdd,]
// 判断是不是群ID  如果是 那么就循环发送给所有人
// 所有消息存数据库,连接的时候就给它所有的信息
// 打开用户  然后筛选这个用户的信息 同时标记已经读
// 前端重连的时候 重新获取数据
$ws_worker->onClose = function ($connection) use (&$connections) {
    // 连接关闭时从连接数组中移除
    unset($connections[$connection->id]);
};

// 新增一个函数用来发送消息给指定连接
function sendMessageToClient($client_id, $message, $connections)
{
    if (isset($connections[$client_id])) {
        $connections[$client_id]->send($message);
    }
}

//  echo $controller->$a();
// 在某个地方调用该函数来向特定连接发送消息
// 示例：假设客户端的 ID 是 "some_client_id"
// sendMessageToClient('some_client_id', 'Hello, this message is for you!', $connections);

Worker::runAll();

// git config --global --unset http.proxy  删除代理